<?php

namespace plugin\muadmin\app\common\middleware;

use plugin\muadmin\app\common\core\AdminAuth;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

/**
 * 后台鉴权中间件
 */
class AdminAuthCheck implements MiddlewareInterface
{
    public function process(Request $request, callable $handler):Response
    {
//        print_r($request->controller.PHP_EOL);
        if(strtolower($request->controller)!='plugin\muadmin\app\admin\controller\install'){
            $file = base_path()."/plugin/{$request->plugin}/config/install.lock";
            if(!is_file($file)){
                return redirect('/app/muadmin/admin/install/index');
            }
        }

        $auth = AdminAuth::getInstance();
        // 通过反射获取控制器哪些方法不需要登录
        $controller = new \ReflectionClass($request->controller);
        $noNeedLogin = $controller->getDefaultProperties()['noNeedLogin'] ?? [];

        if(!in_array('*',  $noNeedLogin)&&!in_array($request->action,  $noNeedLogin)&&!in_array(strtolower($request->action),  $noNeedLogin)){
//            echo 1;
            if(!$auth->isLogin()){
                return redirect('/app/muadmin/admin/index/login');
            }else{
                return $handler($request);
            }
        }
//        echo 2;
        return $handler($request);
    }
}